<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
           <el-form-item label="采购合同号" prop="purchaseContractNum">
              <el-input v-model="queryParams.purchaseContractNum" placeholder="请输入采购合同号" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="运输路段" prop="transportSection">
              <el-select v-model="queryParams.transportSection" placeholder="请选择运输路段" clearable>
                <el-option v-for="dict in transport_section" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <supplier-select v-model:supplierId="queryParams.supplierId" />
            </el-form-item>
            <el-form-item label="付款入账日期" prop="recordDate">
              <el-date-picker clearable v-model="queryParams.recordDate" type="daterange" range-separator="-"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 240px;"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['finance:bill:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['finance:bill:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['finance:bill:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['finance:bill:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" height="400" border :data="billList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="采购合同号" align="center" prop="purchaseContractNum" width="120"/>
        <el-table-column label="项目名称" align="center" prop="projectName" width="160"/>
        <el-table-column label="供应商名称" align="center" prop="supplierName" width="160"/>
        <el-table-column label="运输路段" align="center" prop="transportSection" width="80">
          <template #default="scope">
            <dict-tag :options="transport_section" :value="scope.row.transportSection" />
          </template>
        </el-table-column>
        <el-table-column label="币种" align="center" prop="currency" width="80">
          <template #default="scope">
            <dict-tag :options="bas_currency" :value="scope.row.currency"/>
          </template>
        </el-table-column>
        <el-table-column label="本币价税合计" align="center" prop="localTotalAmount" width="160"/>
        <el-table-column label="付款金额" align="center" prop="billAmount" width="160">
          <template #default="scope">
            <span>{{ Number(scope.row.billAmount || 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入账日期" align="center" prop="recordDate" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="相关凭证号" align="center" prop="voucherNum" width="90"/>
        <el-table-column label="备注" align="center" prop="remark"/>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改付款登记对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="422px" append-to-body>
      <el-form ref="billFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item  label="采购合同号" prop="purchaseContractNum">
            <purchase-contract-select v-model:form="form" />
          </el-form-item>
         <el-form-item label="项目名称" prop="projectName">
            <el-input disabled v-model="form.projectName" placeholder="根据合同号带出" />
          </el-form-item>
          <el-form-item label="运输路段" prop="transportSection">
            <el-select v-model="form.transportSection" placeholder="根据合同号带出" disabled>
              <el-option v-for="dict in transport_section" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input disabled v-model="form.supplierName" placeholder="根据合同号带出" />
          </el-form-item>
          <el-form-item label="本币价税合计" prop="localTotalAmount">
            <el-input disabled style="width: 100%;" :value="formatAmount(form.localTotalAmount)"
              placeholder="根据合同号带出" />
          </el-form-item>
        <el-form-item label="付款金额" prop="billAmount">
          <el-input-number v-model="form.billAmount" :precision="2" placeholder="请输入付款金额" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="付款入账日期" prop="recordDate">
          <el-date-picker clearable v-model="form.recordDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择付款入账日期" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="相关凭证号" prop="voucherNum">
          <el-input v-model="form.voucherNum" placeholder="请输入相关凭证号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Bill" lang="ts">
import { listBill, getBill, delBill, addBill, updateBill } from '@/api/finance/bill';
import { BillVO, BillQuery, BillForm } from '@/api/finance/bill/types';
import { exportPaymentBillExcel } from '@/utils/exportToExcel';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { transport_section, bas_currency } = toRefs<any>(proxy?.useDict('transport_section','bas_currency'));

const billList = ref<BillVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const billFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BillForm = {
  id: undefined,
  billType: 2,
  contractId: undefined,
  billAmount: undefined,
  recordDate: undefined,
  voucherNum: undefined,
  remark: undefined,
}
const data = reactive<PageData<BillForm, BillQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    billType: 2,
    params: {
    }
  },
  rules: {
    purchaseContractNum: [
      { required: true, message: "采购合同号不能为空", trigger: "change" }
    ],
    billAmount: [
      { required: true, message: "付款金额不能为空", trigger: "blur" }
    ],
    recordDate: [
      { required: true, message: "入账日期不能为空", trigger: "blur" }
    ],
    voucherNum: [
      { required: true, message: "相关凭证号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询付款登记列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {
    ...queryParams.value.params,
    recordDateBegin: queryParams.value.recordDate?.[0] || '',
    recordDateEnd: queryParams.value.recordDate?.[1] || '',
  };
  delete queryParams.value.recordDate;
  const res = await listBill(queryParams.value);
  billList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  billFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BillVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加付款登记";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: BillVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getBill(_id);
  const data = {
    ...res.data,
    purchaseContractId: res.data.contractId,
  };

  Object.assign(form.value, data);
  dialog.visible = true;
  dialog.title = "修改付款登记";
};


/** 提交按钮 */
const submitForm = () => {
  billFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value ={
        ...form.value,
        contractId: form.value.purchaseContractId
      }
      if (form.value.id) {
        await updateBill(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addBill(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BillVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除付款登记编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delBill(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}
const formatAmount = (value) => {
  if (value === null || value === undefined || isNaN(Number(value))) {
    return '';
  }
  return Number(value).toFixed(2);
}

/** 导出按钮操作 */
const handleExport = () => {
  exportPaymentBillExcel(billList.value)
}

onMounted(() => {
  getList();
});
</script>
